package com.wuzhipeng.heart.user.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.wuzhipeng.heart.user.convention.exception.ClientException;
import com.wuzhipeng.heart.user.convention.secret.loginSecret;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    private final com.wuzhipeng.heart.user.convention.secret.loginSecret loginSecret;

    public LoginCheckInterceptor(loginSecret loginSecret) {
        this.loginSecret = loginSecret;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String token = request.getHeader("authorization");
            if (token == null) {
                response.sendError(401, "Unauthorized");
                return false;
            }
            if(!JWTUtil.verify(token,loginSecret.getLoginsecret().getBytes()))
            {
                response.sendError(401, "Unauthorized");
                return false;
            }
            JWT jwt = JWTUtil.parseToken(token);
            String phone = jwt.getPayload("phone").toString();
            Long expireTime = Long.parseLong(jwt.getPayload("expirationTime").toString()) ;
            if(expireTime<System.currentTimeMillis())
            {
                response.sendError(401, "Unauthorized");
                return false;
            }
            UserContext.setPhone(phone);


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removePhone();
    }
}
